package thread;

//(懒汉)
class SingletonLazy {
    //引用指向唯一实例
    private volatile static SingletonLazy instance = null; // volatile禁止指令重排序 先初始化为null
    private static Object locker = new Object();
    //双重 if 判定 + volatile 解决线程安全问题
    //if instance为空 首次调用需要考虑线程安全问题(加锁)
    //if !null 后续调用无需加锁
    public static SingletonLazy getInstance() {
        if (instance == null) {
            synchronized (locker) {
                if (instance == null) {
                    instance = new SingletonLazy();
                }
            }
        }
        return instance;
    }
    private SingletonLazy() {
        }
    }
public class Thread_Singleton_lazy {
    public static void main(String[] args) {
        SingletonLazy s1 = SingletonLazy.getInstance();
        SingletonLazy s2 = SingletonLazy.getInstance();
        System.out.println(s1 == s2);
    }
}


